/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.transport.ptcp.psocket.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.text.DecimalFormat;

import cgl.narada.transport.ptcp.psocket.PTCPInputStream;
import cgl.narada.transport.ptcp.psocket.PTCPServerSocket;
import cgl.narada.transport.ptcp.psocket.PTCPSocket;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */
public class PTCPServer {
  public static void print(String[] str, int[] size) {
    for (int i = 0; i < size.length; i++) {
      //System.out.println("Str " + str[i].length() + " size " + size[i]);
    }
    int limit = str[0].length();
    for (int j = size[0]; j > limit; j--) {
      str[0] = str[0] + " ";
    }
    System.out.print(str[0]);

    for (int i = 1; i < size.length; i++) {
      limit = str[i].length();
      //System.out.print(limit+" "+(size[i] - 2)+" ");
      for (int j = (size[i] - 2); j > limit; j--) {
        str[i] = " " + str[i];
      }
      System.out.print(str[i] + "  ");
    }
    System.out.println();
  }

  /*
    public static int[] print(String[] str) {
      int[] size = new int[str.length];
      size[0] = str[0].length() + 5;
      for (int i = 1; i < size.length; i++) {
        size[i] = str[i].length() + 2;
        System.out.println("Size["+i+"]= "+size[i]);
      }
      for (int i = 0; i < size.length; i++) {
        for (int j = size[i]; j > str[i].length(); j--) {
          str[i] = " " + str[i];
        }
        System.out.print(str[i]);
      }
      System.out.println();
      return size;
    }
   */

  public static int[] printLabel(String[] str) {
    int[] size = new int[str.length];
    size[0] = str[0].length() + 6;
    for (int i = 1; i < size.length; i++) {
      size[i] = str[i].length() + 2;
    }

    for (int i = 0; i < size.length; i++) {
      int begin = str[i].length();
      for (int j = begin; j < size[i]; j++) {
        str[i] = str[i] + " ";
      }
      System.out.print(str[i]);
    }

    System.out.println();

    return size;
  }

  public static void main(String[] args) {
    //args = new String[] {"9876"};

    if (args.length < 1) {
      System.out.println("Usage: Server port");
      System.exit( -1);
    }
    int port = Integer.parseInt(args[0]);
    String moduleName = "PTCPServer: ";
    PTCPServerSocket server = new PTCPServerSocket(port);
    System.out.println(moduleName + "Server is started at " + port);
    int count = 0;
    String[] label = new String[] {
        "ModuleName", "Id", "File Size(bytes)",
        "Bandwidth(Mbps)", "Duration(secs)",
        "Streams", "Packet Size(bytes)"};
    //int[] size = new int[] {17, 4, 18, 17, 16, 9, 18};

    /*System.out.println(moduleName + "\tid \tFile Size (bytes) " +
                       "\tBandwidth(Mbps) " + "\tTX Duration(secs) " +
                       "\tNo. of Streams " + "\tPacket Size(bytes)");
     */
    //print(label,size);
    int[] size = printLabel(label);
    while (server != null) {
      PTCPSocket client = server.accept();
      PServerWorker psw = new PServerWorker(client, count, port, size);
      psw.start();
      count++;

    }
  }

  public void printSocketBuffersSize(PTCPSocket client) {
    try {
      System.out.println("Client sending buffer size " +
                         client.getSendBufferSize());
      System.out.println("Client receiving buffer size " +
                         client.getReceiveBufferSize());
    }
    catch (SocketException ex) {
      ex.printStackTrace();
    }
  }
}

class PServerWorker
    extends Thread {
  PTCPSocket psocket = null;
  int id = 0;
  int port = 0;
  int[] spaces = null;
  String moduleName = "PServerWorker: ";

  public PServerWorker(PTCPSocket psocket, int id, int port, int[] spaces) {
    this.psocket = psocket;
    this.id = id;
    this.port = port;
    this.spaces = spaces;
  }

  public void run() {
    try {
      PTCPInputStream pis = (PTCPInputStream) psocket.getInputStream();
      FileOutputStream fos = new FileOutputStream("out_" + id + ".rar");
      //System.out.println(moduleName + id + " PSocket is " +
      //                   (psocket.isConnected() ? "" : "not ") + "connected");
      /*
             if (psocket.isConnected()) {
        System.out.println(moduleName + id + " Client is connected to " +
                           psocket.getInetAddress().getHostName() +
       ":" + port + " with " + psocket.getNumberOfStreams() +
       " streams"); // with buffer size "+pis.getPacketSize());
             }
             }
       */
      //printSocketBuffersSize(client);
      byte[] data = null;
      byte[] output = null;
      byte[] tmp = null;
      int len = 0;

      try {
        while ( (data = pis.receive()) != null) {
          len += data.length;
          //System.out.println("Data length " + data.length);
          fos.write(data);
        }
      }
      catch (IOException ex1) {
      }
      catch (InterruptedException ex1) {
      }

      //System.out.println(moduleName + id + " End of receiving");

      long txStartTime = psocket.getTxStartTime();
      long txEndTime = System.currentTimeMillis();
      double total_time = (txEndTime - txStartTime) / 1000.0;
      double mbits_per_sec = (len * 8.0) / (total_time * 1000000.0);
      DecimalFormat df1 = new DecimalFormat("####.00");
      DecimalFormat df = new DecimalFormat("###,###");
      String[] outs = new String[] {
          moduleName, String.valueOf(id),
          String.valueOf(df.format(len)),
          String.valueOf(df1.format(mbits_per_sec)),
          String.valueOf(total_time),
          String.valueOf(psocket.getNumberOfStreams()),
          String.valueOf(df.format(pis.getPacketSize()))};

      /*System.out.println(moduleName + id + " " + df.format(len) +
                         " bytes at speed " +
                         df1.format(mbits_per_sec) +
                         " Mbps, " + total_time + " (secs), " +
                         psocket.getNumberOfStreams() +
                         " (streams), " + df.format(pis.getPacketSize()) +
                         " (bytes)");
       */
      PTCPServer.print(outs, spaces);
      fos.close();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}
